#include "mainwindow.h"
#include "ui_mainwindow.h"
//#include "pgalayoutdialog.h"
#include <QDebug>
#include <QFileDialog>
#include <QFileInfo>
#include <QProcess>
#include "toast.h"
#include "cameradialog.h"
#include "Camera/cameramanager.h"
#include "resultmanager.h"
#include "aboutdialog.h"
#include "showresultdialog.h"
#include "circlewait.h"
#include "loadlogthread.h"

#include "bgaimageprocess.h"
#include "lgaimageprocess.h"
//#include "calidialog.h"
#include "authoritymanager.h"
#include "serialportdialog.h"
#include "ipdialog.h"
#include "lightsourcedialog.h"
#include "summarydialog.h"
#include "paramdialog.h"
#include "lgaparamdialog.h"
#include "pwddialog.h"
#include "teachingdialog.h"
#include "serialportmanager.h"
#include "bgapackagemanager.h"
#include "imagesavemanager.h"

using namespace HalconCpp;

const int DELAY_MS_NUM = 200;
const int RETRY_NUM = 5;
const double RETRY_DIF = 0.5;
const int TRIGGER_DELAY_MS = 100;
bool deleteDirectory(const QString &path)
{
    if (path.isEmpty())
        return false;

    QDir dir(path);
    if(!dir.exists())
        return true;

    dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
    QFileInfoList fileList = dir.entryInfoList();
    foreach (QFileInfo fi, fileList)
    {
        if (fi.isFile())
            fi.dir().remove(fi.fileName());
        else
            deleteDirectory(fi.absoluteFilePath());
    }
    return dir.rmpath(dir.absolutePath());
}

double GetGrayMean(HImage image)
{
	if (!image.IsInitialized())
	{
		return 0;
	}
	Hlong w, h;
	image.GetImageSize(&w, &h);
	double dev;
	HRegion r;
	GenRectangle1(&r, h*0.25, w*0.25, h*0.75, w*0.75);
	return image.Intensity(r, &dev);
}

void DelayMs(int ms)
{
	//QTime t;
	//t.start();
	//while (t.elapsed() < ms)
	//{
	//	QCoreApplication::processEvents();
	//}
	/*QTime _Timer = QTime::currentTime().addMSecs(ms);
	while (QTime::currentTime() < _Timer)
	{
		QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
	}*/
	QEventLoop loop;
	QTimer::singleShot(ms, &loop, SLOT(quit()));
	loop.exec();
}

void MainWindow::resizeEvent(QResizeEvent* event)
{
	Q_UNUSED(event);
	AdjustImageUI(!ui->checkBox->isChecked());
}

void MainWindow::UpdateTypeAndPackage()
{
	QString appName = QCoreApplication::applicationName();
	QSettings app(appName, "Config");
	QString package = app.value("Package").toString();
	QString chipType = app.value("ChipType").toString();

	QString str = QString("%1/Config/package").arg(QCoreApplication::applicationDirPath());
	{
		QStringList list;
		QDir dir(str);

		if (dir.exists())
		{
			dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
			QFileInfoList fileList = dir.entryInfoList();
			foreach(QFileInfo fi, fileList)
			{
				if (fi.isDir())
				{
					//if (fi.suffix().compare("cfg", Qt::CaseInsensitive) == 0)
					{
						list.append(fi.completeBaseName());
					}
				}
			}
		}
		ui->comboBoxType->addItems(list);

		if (list.count() >= 1)
		{
			if (list.contains(chipType))
			{
				ui->comboBoxType->setCurrentText(chipType);
			}
			else
			{
				ui->comboBoxType->setCurrentIndex(0);
			}
			app.setValue("ChipType", ui->comboBoxType->currentText());
		}
	}
	if (ui->comboBoxType->count() > 0)
	{
		str = str.append("/").append(ui->comboBoxType->currentText());
		QStringList list;
		QDir dir(str);

		if (dir.exists())
		{
			dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
			QFileInfoList fileList = dir.entryInfoList();
			foreach(QFileInfo fi, fileList)
			{
				if (fi.isFile())
				{
					if (fi.suffix().compare("cfg", Qt::CaseInsensitive) == 0)
					{
						list.append(fi.completeBaseName());
					}
				}
			}
		}
		ui->comboBox->addItems(list);

		if (list.count() >= 1)
		{
			if (list.contains(package))
			{
				ui->comboBox->setCurrentText(package);
			}
			else
			{
				ui->comboBox->setCurrentIndex(0);
			}
			app.setValue("Package", ui->comboBox->currentText());
		}
	}
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
	m_re.successTimes = m_re.failTimes = m_re.totalTimes = 0;
	m_re.ballDamageTimes = m_re.capDamageTimes = m_re.substrateDamageTimes = 0;
	
	SerialPortManager::getInstance();

	SetupUI();
#if 0
	//自定义标题栏  
	setWindowFlags(Qt::FramelessWindowHint  | windowFlags());

    TitleWidget *pTitleBar = new TitleWidget(this);
   // installEventFilter(pTitleBar);
	QVBoxLayout *vbox = qobject_cast<QVBoxLayout *>( this->centralWidget()->layout());
	vbox->insertWidget(0, pTitleBar);
	vbox->setStretch(0, 1);
	vbox->setStretch(1, 1);
	vbox->setStretch(2, 20);
#endif

#ifdef QT_NO_DEBUG
	{
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Debug");
		int t = app.value("testmode").toInt();
		if (t == 0)
		{
			ui->verticalLayout->removeItem(ui->horizontalLayout);
			ui->horizontalLayout->removeWidget(ui->pushButton);
			ui->horizontalLayout->removeWidget(ui->pushButton_2);
			ui->horizontalLayout->removeWidget(ui->pushButton_StaticProcess);
			ui->pushButton->setHidden(true);
			ui->pushButton_2->setHidden(true);
			ui->pushButton_3->setHidden(true);
			ui->pushButton_StaticProcess->setHidden(true);
		}
	}

#endif // DEBUG

	UpdateTypeAndPackage();


	//BgaPackageManager::getInstance()->SetPackageType(ui->comboBox->currentText());

	QString v = QCoreApplication::applicationVersion();
	setWindowTitle("BLQ Vision System For JHT " + v);

	m_labelBypass = new QLabel(this);
	m_labelBypass->setFrameStyle(QFrame::Panel | QFrame::Sunken);
	m_labelBypass->setAlignment(Qt::AlignHCenter);
	ui->statusBar->addPermanentWidget(m_labelBypass);

	m_labelState = new QLabel(this);
	m_labelState->setFrameStyle(QFrame::StyledPanel);
	m_labelState->setAlignment(Qt::AlignHCenter);
	ui->statusBar->addPermanentWidget(m_labelState);
	//ui->statusBar->showMessage("BGA Vision System For JHT");
	UpdateStatusBar();
	static const QDate buildDate = QLocale(QLocale::English).toDate(QString(__DATE__).replace("  ", " 0"), "MMM dd yyyy");
	static const QTime buildTime = QTime::fromString(__TIME__, "hh:mm:ss");
	ui->statusBar->showMessage("Build Time: " + buildTime.toString("hh:mm:ss") + " " + buildDate.toString("yyyy.MM.dd"));

    ClearExpiredFiles();

    AddSlots();
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::TeachingTest()
{
	//qDebug() << __FUNCTION__;
	CameraManager *manager = CameraManager::getInstance();
	if (!manager->IsConnected())
	{
		manager->Connect();
	}
	if (manager->IsConnected())
	{
		//ui->widget_Realtime->SetProcessing(false);
		ui->widget_Realtime->SetDispImageSize(5120, 5120);
		AdjustImageUI(false);
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();
		ui->checkBox->setChecked(false);


		StartAction(1);
		emit TeachingFinishedEvent();

		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Config");
		QString chipType = app.value("ChipType").toString();

		if (chipType.toLower() == "bga")
		{
			ResultManager::ERROR_TYPE res = BgaImageProcess::getInstance()->GetLastResult();

			//emit TeachingFinishedEvent();
			if (res == ResultManager::ERR_PASS || res == ResultManager::ERR_SUBSTRATE_DAMAGE)
			{
				BgaPackageManager *m = BgaPackageManager::getInstance();
				BgaImageProcess *imp = BgaImageProcess::getInstance();
				BgaPackageManager::POD_INFO pod = imp->GetPod();
				QString str = QString("Maximum shadow ratio(%2%)\nUse the current configuration for package (%1)?").arg(m->GetPackageType()).arg(pod.maxShadowRatio, 0, 'g', 4); QMessageBox::StandardButton rb = QMessageBox::question(NULL, "", str, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
				if (rb == QMessageBox::Yes)
				{
					PACKAGE_INFO info = StaticFunction::GetPackageInfoFromFile();

					if (info.capNumbers > 0)
					{
						info.capArea = pod.meanCapArea;
					}
					StaticFunction::SavePackageInfo(info);
					m->SavePodToFile(pod);
				}
			}
			else {
				Toast *w = new Toast(this, tr("Test result: Fail"), 250, 36);
				w->toast();
				return;
			}
		}
	}
}

void MainWindow::SetupUI()
{
//	resize(800, 600);

	ui->lcdNumber_Time->display(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

	ui->widget_Realtime->InitHalconWindow();

	QStringList header;
	header << tr("Date") << tr("Time") << tr("Result");
	ui->tableWidget->setHorizontalHeaderLabels(header);
	ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
	ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
	QHeaderView * h = ui->tableWidget->horizontalHeader();
	h->setSectionResizeMode(QHeaderView::Stretch);
	h->setSectionResizeMode(0, QHeaderView::ResizeToContents);     //然后设置要根据内容使用宽度的列

	QRegExp regx("[1-9][0-9]+$");
	QValidator *validator = new QRegExpValidator(regx, ui->lineEditChipNum);
	ui->lineEditChipNum->setValidator(validator);

	ui->pushButton_Reset->setHidden(true);
	ui->lineEditChipNum->setHidden(true);
	ui->checkBoxTest->setHidden(true);
}

void MainWindow::UpdateStatusBar()
{
	BgaPackageManager::INSPECT_PARAM inspectParam = BgaPackageManager::getInstance()->GetParamFromFile();
	if (inspectParam.bBypass)
	{
		m_labelBypass->setText("<font color=#353535 size=3>Bypass</font><br><font color=#FF0000 size=5>ON</font>");
	}
	else
	{
		m_labelBypass->setText("<font color=#353535 size=3>Bypass</font><br><font color=#101010 size=5>OFF</font>");
	}

	QVariant v = ui->pushButton_Start->property("Started");
	if (v.toBool())
	{
		m_labelState->setText("<font color=#353535 size=3>State</font><br><font color=#101010 size=5>Running</font>");
	}
	else
	{
		m_labelState->setText("<font color=#353535 size=3>State</font><br><font color=#FF0000 size=5>Idle</font>");
	}
}

RUN_INFO MainWindow::GetRunInfo()
{
	RUN_INFO ri;
	ri.operatorName = ui->lineEditOperator->text();
	ri.productNum = ui->comboBoxType->currentText();
	ri.packageName = ui->comboBox->currentText();
	ri.chipNum = ui->lineEditChipNum->text().toInt();
	ri.bVarify = ui->checkBoxTest->isChecked();
	ri.lotName = m_re.lotId;
	return ri;
}

void  MainWindow::AdjustImageUI(bool )
{
	return;
	//BgaPackageManager::INSPECT_PARAM inspectParam = BgaPackageManager::getInstance()->GetParamFromFile();
	//if (inspectParam.bKeepImageRatio)
	//{
	//	QRect rect1 = ui->btnLightsOff->geometry();
	//	QRect rect3 = ui->verticalLayout->geometry();
	//	QRect rect4 = ui->widget_Realtime->geometry();
	//	QRect rect = QRect(rect3.x() + 5, rect1.bottom() + 6, rect3.width() - 10, ui->tableWidget->geometry().bottom() - rect1.bottom() - 6);
	//	if (bResultImage && inspectParam.bResultCali)
	//	{
	//		ui->widget_Realtime->setGeometry(rect.x() + rect.width() / 2 - rect.height() * 5120 / 5120 / 2, rect.y(), rect.height() * 5120 / 5120, rect.height());
	//	}
	//	else 
	//	{
	//		ui->widget_Realtime->setGeometry(rect.x(), rect.y() + (rect.height() - rect.width() * 5120 / 5120) / 2, rect.width(), rect.width() * 5120 / 5120);
	//	}
	//}
}

void MainWindow::AddSlots()
{
	//connect(ImageProcess::getInstance(), &ImageProcess::UpdateMainWndEvent, this, [=]() {
	//	AdjustImageUI(true);
	//}, Qt::UniqueConnection);

	connect(ui->listWidget, &QListWidget::customContextMenuRequested, [=](QPoint /*pos*/) {
		/*QListWidgetItem* curItem = ui->listWidget->itemAt(pos);
		if (curItem == NULL)
			return;*/

		QMenu *popMenu = new QMenu(this);
		QAction *clearSeeds = new QAction(tr("Clear"), this);
		popMenu->addAction(clearSeeds);
		connect(clearSeeds, &QAction::triggered, this, [=]() {
			ui->listWidget->clear();
		});
		popMenu->exec(QCursor::pos());
		delete popMenu;
		delete clearSeeds;
	});

	WaitForComData();

	connect(ui->comboBoxType, &QComboBox::currentTextChanged, [=](QString str1) {
		{
			QString appName = QCoreApplication::applicationName();
			QSettings app(appName, "Config");
			app.setValue("ChipType", ui->comboBoxType->currentText());
		}
		ui->comboBox->clear();
		QString str = QString("%1/Config/package/%2").arg(QCoreApplication::applicationDirPath(), str1);
		if (ui->comboBoxType->count() > 0)
		{
			QStringList list;
			QDir dir(str);

			if (dir.exists())
			{
				dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
				QFileInfoList fileList = dir.entryInfoList();
				foreach(QFileInfo fi, fileList)
				{
					if (fi.isFile())
					{
						if (fi.suffix().compare("cfg", Qt::CaseInsensitive) == 0)
						{
							list.append(fi.completeBaseName());
						}
					}
				}
			}
			ui->comboBox->addItems(list);

			ui->comboBox->setCurrentIndex(0);
			QString appName = QCoreApplication::applicationName();
			QSettings app(appName, "Config");
			app.setValue("Package", ui->comboBox->currentText());
			//BgaPackageManager::getInstance()->SetPackageType(ui->comboBox->currentText());	
		}
	});

	connect(ui->comboBox, &QComboBox::currentTextChanged, [=](QString str) {
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Config");
		app.setValue("Package", str);
		//BgaPackageManager::getInstance()->SetPackageType(str);
	});

	connect(ui->tableWidget, &QTableWidget::cellDoubleClicked, [=](int row, int){
		QString str2 = ui->tableWidget->item(row, 0)->text();
		QString str3 = ui->tableWidget->item(row, 1)->text();
		str3 = str3.replace(":", "_");
		QString str4 = ui->tableWidget->item(row, 2)->text();
		QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());
		QString path = QString("%1/%2/%3_%4.bmp").arg(dir_str).arg(str2).arg(str3).arg(str4);

		QDesktopServices::openUrl(QUrl(path));
	});
    CameraManager *manager = CameraManager::getInstance();

  /*  QString ss1 = "background-color: rgb(180, 0, 0);\
            font: 18pt \"微软雅黑\";\
            color: rgb(255, 255, 255);\
    border-radius: 15px";

        QString ss2 = "background-color: rgb(0, 170, 255);\
        font: 18pt \"微软雅黑\";\
        color: rgb(255, 255, 255);\
    border-radius: 15px";*/

    ui->pushButton_Start->setProperty("Started", false);
	/*ui->widget_Realtime->SetLive(ui->checkBox->isChecked());
	connect(ui->checkBox, &QCheckBox::stateChanged, [=]() {
		ui->widget_Realtime->SetLive(ui->checkBox->isChecked());
	});*/
	connect(ui->checkBox, &QCheckBox::stateChanged, [=]() {
		//ui->widget_Realtime->SetLive(ui->checkBox->isChecked());
		if (ui->checkBox->isChecked())
		{
			ui->widget_Realtime->SetDispImageSize(5120, 5120);
			AdjustImageUI(false);
#ifndef QT_NO_DEBUG
			SerialPortManager *sp = SerialPortManager::getInstance();
			sp->SetFourLightBrightnessSync(50, 50, 50, 50);
#endif
		}
		manager->SetCameraLive(ui->checkBox->isChecked());
	});


    connect(ui->pushButton_Start, &QPushButton::clicked, [=](){

		QVariant v = ui->pushButton_Start->property("Started");
		bool b = v.toBool();
		if(!b)
		{
			ui->pushButton_Start->setDisabled(true);
			//   ui->pushButton_StaticProcess->setDisabled(true);
			QString appName = QCoreApplication::applicationName();
			QSettings app(appName, "Camera");
			QString sn = app.value("camera").toString();
			if (!sn.isEmpty())
			{
				manager->SelectCameraWithSerialNum(sn);
			}
			if (!manager->IsConnected())
			{
				manager->Connect();
			}

			if (manager->IsConnected())
			{
				ui->pushButton_Start->setText(tr("Stop"));
				ui->pushButton_Start->setIcon(QIcon(":/images/stop.png"));
				ui->pushButton_Start->setDisabled(false);
				ui->widget_Realtime->SetDispImageSize(5120, 5120);
			}
		}
		else
		{
			//ui->pushButton_Start->setStyleSheet(ss2);
			ui->pushButton_Start->setText(tr("Start"));
			ui->pushButton_Start->setIcon(QIcon(":/images/start.png"));
			//  m_timerStart->stop();
		  //    ui->pushButton_StaticProcess->setDisabled(false);
			//ui->widget_Realtime->SetProcessing(false);
			//StopCom();
			/*QSerialPort *m = SerialPortManager::getInstance()->GetHandlerCom();
			disconnect(m, &QSerialPort::readyRead, 0, 0);*/
			manager->Disconnect();
		}

		ui->pushButton_Start->setProperty("Started", manager->IsConnected());
		UpdateStatusBar();
    });



 /*   connect(ui->pushButton_Camera, &QPushButton::clicked, [=]()
    {
        CameraDialog *pgaDlg = new CameraDialog(this);
        pgaDlg->exec();
    });*/
	QString appName = QCoreApplication::applicationName();

	connect(ui->pushButton_Cali, &QPushButton::clicked, [=]() {
#ifdef QT_NO_DEBUG
		QSettings app(appName, "Debug");
		int t = app.value("testmode").toInt();
		if (t == 0)
		{
			AuthorityManager *m = AuthorityManager::getInstance();
			if (m->getCurrentLevel() == AuthorityManager::AUTH_USER)
			{
				PwdDialog *pgaDlg = new PwdDialog(this);
				pgaDlg->exec();
				if (m->getCurrentLevel() == AuthorityManager::AUTH_USER)
				{
					return;
				}
			}
		}
#endif
		QMenu *menu = new QMenu();
		QAction *camera = new QAction(QIcon(":/images/camera.png"), "Camera");
		QAction *light = new QAction(QIcon(":/images/light.png"), "Light Source");
		//	QAction *ic = new QAction(QIcon(":/images/ic.png"), "IC Layout");
		//	QAction *cali = new QAction(QIcon(":/images/cali.png"), "Calibration");
		QAction *com = new QAction(QIcon(":/images/com.png"), "Serial Port");
		QAction *param = new QAction(QIcon(":/images/param.png"), "Parameter");
		QAction *about = new QAction(QIcon(":/images/about.png"), "About");
		QAction *teach = new QAction(QIcon(":/images/teaching.png"), "Teaching");

		menu->addAction(camera);
		menu->addAction(com);
		menu->addAction(light);
		menu->addAction(param);
		QSettings app2(appName, "Config");

#ifdef QT_NO_DEBUG
		
		if (t == 0)
		{
			AuthorityManager *m = AuthorityManager::getInstance();
			if (m->getCurrentLevel() >= AuthorityManager::AUTH_RD)
			{
				menu->addAction(teach);
			}
		}
		else {
			menu->addAction(teach);
		}
#else
		menu->addAction(teach);
#endif
	
        menu->addAction(about);


        connect(camera, &QAction::triggered,this, [=](){
            CameraDialog *dlg = new CameraDialog(this);
            dlg->exec();
        });
        connect(com, &QAction::triggered,this, [=](){
            SerialPortDialog *dlg = new SerialPortDialog(this);
            dlg->exec();
        });

        connect(light, &QAction::triggered,this, [=](){
            LightSourceDialog *dlg = new LightSourceDialog(this);
            dlg->show();
        });

        connect(param, &QAction::triggered,this, [=](){
			QString appName = QCoreApplication::applicationName();
			QSettings app(appName, "Config");
			QString chipType = app.value("ChipType").toString();

			if (chipType.toLower() == "bga")
			{
				ParamDialog *dlg = new ParamDialog(this);
				dlg->exec();
			}
			else if (chipType.toLower() == "lga")
			{
				LgaParamDialog *dlg = new LgaParamDialog(this);
				dlg->exec();
			}
			UpdateStatusBar();
        });

		connect(teach, &QAction::triggered, this, [=]() {
			TeachingDialog *dlg = new TeachingDialog(this);
			dlg->show();
		});

        connect(about, &QAction::triggered,this, [=](){
            AboutDialog *dlg = new AboutDialog(this);
            dlg->exec();
        });
        menu->exec(QCursor::pos());  
    });

    connect(ui->pushButton_StaticProcess, &QPushButton::clicked, [=](){
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Debug");
		int count = app.value("StaticProcess").toInt();
		if (count <= 1)
		{
			count = 1;
		}

		for (int i=0; i<count; i++)
		{
			m_re.operatorName = ui->lineEditOperator->text();
			m_re.productNum = ui->comboBoxType->currentText();
			m_re.packageName = ui->comboBox->currentText();
			if (!manager->IsConnected())
			{
				manager->Connect();
			}
			if (manager->IsConnected())
			{
				StartAction(1);
			}
			QThread::msleep(1000);
		}
    });

    connect(ui->pushButton_Logs, &QPushButton::clicked, [=](){
		QString dir_str = QString("%1/Results").arg(QCoreApplication::applicationDirPath());
		QString path = QFileDialog::getOpenFileName(this, tr("log File"), dir_str, "*.wtlog", Q_NULLPTR);
		if (path.isEmpty())
		{
			return;
		}

		CircleWait *wait = new CircleWait(this);
		wait->setColor(QColor("red"));
		wait->show();

		LoadLogThread *thread = new LoadLogThread(this);
		thread->SetLogFile(path, true);
		connect(thread, &LoadLogThread::UpdateDateUI, this, [=](QMap<QString, ResultManager::DATE_RESULT_DEF> v) {
			wait->close();

			SummaryDialog *rw = new SummaryDialog(this);
			rw->SetReslut(v);
			rw->exec();

		});
		thread->start(); 
    });
	///multi groups
	connect(ui->pushButton, &QPushButton::clicked, [=]() {
		QTextCodec *code = QTextCodec::codecForName("GB2312");
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Config");
		QString chipType = app.value("ChipType").toString();

		if (chipType.toLower() == "bga")
		{
			BgaImageProcess *imp = BgaImageProcess::getInstance();

			QString folder = QFileDialog::getExistingDirectory(this, tr("log File"), Q_NULLPTR);
			if (folder.isEmpty())
			{
				return;
			}


			QDir dir(folder);
			if (!dir.exists())
			{
				return;
			}
			dir.setFilter(QDir::Files | QDir::NoSymLinks);
			QFileInfoList list = dir.entryInfoList();

			int file_count = list.count();
			if (file_count <= 0)
			{
				return;
			}

			QStringList string_list;
			for (int i = 0; i < file_count; i++)
			{
				QFileInfo file_info = list.at(i);

				QString filename = file_info.completeBaseName();
				QString ext = file_info.suffix();
				QString strKey = "_edge1";
				if (filename.contains(strKey))
				{
					QString folder = file_info.absolutePath();
					QString suffix = file_info.completeSuffix();
					QString str1 = file_info.fileName();
					QString ext = file_info.suffix();
					QString str = str1.mid(0, str1.lastIndexOf("_"));

					qDebug() << "FailManager::" << str1;
					PACKAGE_INFO info = StaticFunction::GetPackageInfo();
					int k = info.listAction.length() == 0 ? 1 : info.listAction.length();
					for (int i = 1; i <= k; i++)
					{
						ACTION_CONFIG ac;
						ac.catchBall = ac.catchSubstrate = 1;
					//	ac.catchCM = info.crossMark > 0;
						ac.catchCap = info.capNumbers > 0;
						if (info.listAction.length() > 0)
						{
							ac = info.listAction[i - 1];
						}
						if (ac.catchSubstrate == 1)
						{
							QString s = QString("%1/%2_edge%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
							QFileInfo fileInfo(s);
							if (fileInfo.exists())
							{
								std::string name = code->fromUnicode(s).data();
								HTuple FileName = HTuple(name.data());
								HImage Image;
								ReadImage(&Image, FileName);
								imp->SetSubstrateImage(Image, i);
							}
							if (i == 1)
							{
								QString s = QString("%1/%2_edge.%3").arg(folder).arg(str).arg(suffix);
								QFileInfo fileInfo(s);
								if (fileInfo.exists())
								{
									std::string name = code->fromUnicode(s).data();
									HTuple FileName = HTuple(name.data());
									HImage Image;
									ReadImage(&Image, FileName);
									imp->SetSubstrateImage(Image, i);
								}
							}
						}
						if (ac.catchBall == 1)
						{
							QString s = QString("%1/%2_ball%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
							QFileInfo fileInfo(s);
							if (fileInfo.exists())
							{
								std::string name = code->fromUnicode(s).data();
								HTuple FileName = HTuple(name.data());
								HImage Image;
								ReadImage(&Image, FileName);
								imp->SetBallImage(Image, i);
							}
							if (i == 1)
							{
								QString s = QString("%1/%2_ball.%3").arg(folder).arg(str).arg(suffix);
								QFileInfo fileInfo(s);
								if (fileInfo.exists())
								{
									std::string name = code->fromUnicode(s).data();
									HTuple FileName = HTuple(name.data());
									HImage Image;
									ReadImage(&Image, FileName);
									imp->SetBallImage(Image, i);
								}
							}

						}
						if (ac.catchCap == 1)
						{
							QString s = QString("%1/%2_cap%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
							QFileInfo fileInfo(s);
							if (fileInfo.exists())
							{
								std::string name = code->fromUnicode(s).data();
								HTuple FileName = HTuple(name.data());
								HImage Image;
								ReadImage(&Image, FileName);
								imp->SetCapImage(Image, i);
							}
							if (i == 1)
							{
								QString s = QString("%1/%2_cap.%3").arg(folder).arg(str).arg(suffix);
								QFileInfo fileInfo(s);
								if (fileInfo.exists())
								{
									std::string name = code->fromUnicode(s).data();
									HTuple FileName = HTuple(name.data());
									HImage Image;
									ReadImage(&Image, FileName);
									imp->SetCapImage(Image, i);
								}
							}
						}
						/*if (ac.catchCM == 1)
						{
							QString s = QString("%1/%2_cm%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
							QFileInfo fileInfo(s);
							if (fileInfo.exists())
							{
								std::string name = code->fromUnicode(s).data();
								HTuple FileName = HTuple(name.data());
								HImage Image;
								ReadImage(&Image, FileName);
								imp->SetCrossMarkImage(Image, i);
							}
							if (i == 1)
							{
								QString s = QString("%1/%2_cm.%3").arg(folder).arg(str).arg(suffix);
								QFileInfo fileInfo(s);
								if (fileInfo.exists())
								{
									std::string name = code->fromUnicode(s).data();
									HTuple FileName = HTuple(name.data());
									HImage Image;
									ReadImage(&Image, FileName);
									imp->SetCrossMarkImage(Image, i);
								}
							}
						}*/
					}
					QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

					QDateTime t = QDateTime::currentDateTime();

					imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());

					ResultManager::ERROR_TYPE res = imp->GetInspectResult();
					//	bool b = res == ResultManager::ERR_PASS;
					QString path = QString("%1/Results/result.wtlog").arg(QCoreApplication::applicationDirPath());
					SaveResultToFile(res, path, t);

					UpdateUIWithResult(res, t, FALSE);

					DelayMs(100);

				}
			}
		}
		else if (chipType.toLower() == "lga")
		{
		LgaImageProcess *imp = LgaImageProcess::getInstance();

		QString folder = QFileDialog::getExistingDirectory(this, tr("log File"), Q_NULLPTR);
		if (folder.isEmpty())
		{
			return;
		}


		QDir dir(folder);
		if (!dir.exists())
		{
			return;
		}
		dir.setFilter(QDir::Files | QDir::NoSymLinks);
		QFileInfoList list = dir.entryInfoList();

		int file_count = list.count();
		if (file_count <= 0)
		{
			return;
		}

		QStringList string_list;
		for (int i = 0; i < file_count; i++)
		{
			QFileInfo file_info = list.at(i);

			QString filename = file_info.completeBaseName();
			QString ext = file_info.suffix();
			QString strKey = "_edge1";
			if (filename.contains(strKey))
			{
				QString folder = file_info.absolutePath();
				QString suffix = file_info.completeSuffix();
				QString str1 = file_info.fileName();
				QString ext = file_info.suffix();
				QString str = str1.mid(0, str1.lastIndexOf("_"));

				qDebug() << "FailManager::" << str1;
				PACKAGE_INFO info = StaticFunction::GetPackageInfo();
				int k = info.listAction.length() == 0 ? 1 : info.listAction.length();
				for (int i = 1; i <= k; i++)
				{
					ACTION_CONFIG ac;
					ac.catchBall = ac.catchSubstrate = 1;
					//ac.catchCM = info.crossMark > 0;
					ac.catchCap = info.capNumbers > 0;
					if (info.listAction.length() > 0)
					{
						ac = info.listAction[i - 1];
					}
					if (ac.catchSubstrate == 1)
					{
						QString s = QString("%1/%2_edge%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
						QFileInfo fileInfo(s);
						if (fileInfo.exists())
						{
							std::string name = code->fromUnicode(s).data();
							HTuple FileName = HTuple(name.data());
							HImage Image;
							ReadImage(&Image, FileName);
							imp->SetSubstrateImage(Image, i);
						}
						if (i == 1)
						{
							QString s = QString("%1/%2_edge.%3").arg(folder).arg(str).arg(suffix);
							QFileInfo fileInfo(s);
							if (fileInfo.exists())
							{
								std::string name = code->fromUnicode(s).data();
								HTuple FileName = HTuple(name.data());
								HImage Image;
								ReadImage(&Image, FileName);
								imp->SetSubstrateImage(Image, i);
							}
						}
					}
					if (ac.catchBall == 1)
					{
						QString s = QString("%1/%2_pad%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
						QFileInfo fileInfo(s);
						if (fileInfo.exists())
						{
							std::string name = code->fromUnicode(s).data();
							HTuple FileName = HTuple(name.data());
							HImage Image;
							ReadImage(&Image, FileName);
							imp->SetBallImage(Image, i);
						}
						if (i == 1)
						{
							QString s = QString("%1/%2_pad.%3").arg(folder).arg(str).arg(suffix);
							QFileInfo fileInfo(s);
							if (fileInfo.exists())
							{
								std::string name = code->fromUnicode(s).data();
								HTuple FileName = HTuple(name.data());
								HImage Image;
								ReadImage(&Image, FileName);
								imp->SetBallImage(Image, i);
							}
						}

					}
					if (ac.catchCap == 1)
					{
						QString s = QString("%1/%2_cap%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
						QFileInfo fileInfo(s);
						if (fileInfo.exists())
						{
							std::string name = code->fromUnicode(s).data();
							HTuple FileName = HTuple(name.data());
							HImage Image;
							ReadImage(&Image, FileName);
							imp->SetCapImage(Image, i);
						}
						if (i == 1)
						{
							QString s = QString("%1/%2_cap.%3").arg(folder).arg(str).arg(suffix);
							QFileInfo fileInfo(s);
							if (fileInfo.exists())
							{
								std::string name = code->fromUnicode(s).data();
								HTuple FileName = HTuple(name.data());
								HImage Image;
								ReadImage(&Image, FileName);
								imp->SetCapImage(Image, i);
							}
						}
					}
					
				}
				QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

				QDateTime t = QDateTime::currentDateTime();

				imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());

				ResultManager::ERROR_TYPE res = imp->GetInspectResult();
				//	bool b = res == ResultManager::ERR_PASS;
				QString path = QString("%1/Results/result.wtlog").arg(QCoreApplication::applicationDirPath());
				SaveResultToFile(res, path, t);

				UpdateUIWithResult(res, t, FALSE);

				DelayMs(100);

			}
		}
		}
	});
	///single group
	connect(ui->pushButton_2, &QPushButton::clicked, [=]() {
		QString path1 = QFileDialog::getOpenFileName(this, tr("images"), "", "*.bmp *.png", nullptr);
		if (path1.isEmpty())
		{
			return;
		}
		QFileInfo file(path1);
		QTextCodec *code = QTextCodec::codecForName("GB2312");
		QString folder = file.absolutePath();
		QString suffix = file.completeSuffix();
		QString str1 = file.fileName();
		QString ext = file.suffix();
		QString str = str1.mid(0, str1.lastIndexOf("_"));
		qDebug() << path1;
		BgaImageProcess *imp = BgaImageProcess::getInstance();
		LgaImageProcess *imp2 =LgaImageProcess::getInstance();
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Config");
		QString chipType = app.value("ChipType").toString();


		int type = chipType.toLower() == "bga" ? 1 : chipType.toLower() == "lga" ? 2 : 3;
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();
		int k = info.listAction.length() == 0 ? 1 : info.listAction.length();
		for (int i = 1; i <= k; i++)
		{
			ACTION_CONFIG ac;
			ac.catchBall = ac.catchSubstrate = 1;
		//	ac.catchCM = info.crossMark > 0;
			ac.catchCap = info.capNumbers > 0;
			if (info.listAction.length() > 0)
			{
				ac = info.listAction[i - 1];
			}
			
			//if (ac.catchSubstrate == 1)
			{
				QString s = QString("%1/%2_edge%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
				QFileInfo fileInfo(s);
				if (fileInfo.exists())
				{
					std::string name = code->fromUnicode(s).data();
					HTuple FileName = HTuple(name.data());
					HImage Image;
					ReadImage(&Image, FileName);
					if (type == 1)
					{
						imp->SetSubstrateImage(Image, i);
					}
					else if (type == 2)
					{
						imp2->SetSubstrateImage(Image, i);
					}
					
				}
				/*if (i == 1)
				{
					QString s = QString("%1/%2_edge.%3").arg(folder).arg(str).arg(suffix);
					QFileInfo fileInfo(s);
					if (fileInfo.exists())
					{
						std::string name = code->fromUnicode(s).data();
						HTuple FileName = HTuple(name.data());
						HImage Image;
						ReadImage(&Image, FileName);
						imp->SetSubstrateImage(Image, i);
					}
				}*/
			}
			//if (ac.catchBall== 1)
			{
				QString s = QString("%1/%2_pad%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
				QFileInfo fileInfo(s);
				if (fileInfo.exists())
				{
					std::string name = code->fromUnicode(s).data();
					HTuple FileName = HTuple(name.data());
					HImage Image;
					ReadImage(&Image, FileName);
				//	imp->SetBallImage(Image, i);
					if (type == 1)
					{
						imp->SetBallImage(Image, i);
					}
					else if (type == 2)
					{
						imp2->SetBallImage(Image, i);
					}
				}
				/*if (i == 1)
				{
					QString s = QString("%1/%2_ball.%3").arg(folder).arg(str).arg(suffix);
					QFileInfo fileInfo(s);
					if (fileInfo.exists())
					{
						std::string name = code->fromUnicode(s).data();
						HTuple FileName = HTuple(name.data());
						HImage Image;
						ReadImage(&Image, FileName);
						imp->SetBallImage(Image, i);
					}
				}*/
			}
			//if (ac.catchCap == 1)
			{
				QString s = QString("%1/%2_cap%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
				QFileInfo fileInfo(s);
				if (fileInfo.exists())
				{
					std::string name = code->fromUnicode(s).data();
					HTuple FileName = HTuple(name.data());
					HImage Image;
					ReadImage(&Image, FileName);
					//imp->SetCapImage(Image, i);
					if (type == 1)
					{
						imp->SetCapImage(Image, i);
					}
					else if (type == 2)
					{
						imp2->SetCapImage(Image, i);
					}
				}
				/*if (i == 1)
				{
					QString s = QString("%1/%2_cap.%3").arg(folder).arg(str).arg(suffix);
					QFileInfo fileInfo(s);
					if (fileInfo.exists())
					{
						std::string name = code->fromUnicode(s).data();
						HTuple FileName = HTuple(name.data());
						HImage Image;
						ReadImage(&Image, FileName);
						imp->SetCapImage(Image, i);
					}
				}*/
			}
			//if (ac.catchCM == 1)
			//{
			//	QString s = QString("%1/%2_cm%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
			//	QFileInfo fileInfo(s);
			//	if (fileInfo.exists())
			//	{
			//		std::string name = code->fromUnicode(s).data();
			//		HTuple FileName = HTuple(name.data());
			//		HImage Image;
			//		ReadImage(&Image, FileName);
			//		imp->SetCrossMarkImage(Image, i);
			//	}
			//	/*if (i == 1)
			//	{
			//		QString s = QString("%1/%2_cm.%3").arg(folder).arg(str).arg(suffix);
			//		QFileInfo fileInfo(s);
			//		if (fileInfo.exists())
			//		{
			//			std::string name = code->fromUnicode(s).data();
			//			HTuple FileName = HTuple(name.data());
			//			HImage Image;
			//			ReadImage(&Image, FileName);
			//			imp->SetCrossMarkImage(Image, i);
			//		}
			//	}*/
			//}
		}
		QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

		QDateTime t = QDateTime::currentDateTime();
		ResultManager::ERROR_TYPE res;// = imp->GetInspectResult();
		if (type == 1)
		{
			//QDateTime t = QDateTime::currentDateTime();
			imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());
			res = imp->GetInspectResult();
		}
		else if (type == 2)
		{
			res = imp2->GetInspectResult();
			t = QDateTime::currentDateTime();
			imp2->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());
		}

		QString path = QString("%1/Results/result.wtlog").arg(QCoreApplication::applicationDirPath());
		SaveResultToFile(res, path, t);
		if (type == 2)
		{
			imp2->ShowAndSave(TRUE);
		}
		UpdateUIWithResult(res, t, FALSE);

		if (res == ResultManager::ERR_PASS)
		{
			if (type == 1)
			{
				BgaPackageManager::POD_INFO pod = imp->GetPod();
				BgaPackageManager *m = BgaPackageManager::getInstance();
				m->SavePodToFile(pod);
			}
		/*	else if (type == 2)
			{
				LgaPackageManager::POD_INFO pod = imp2->GetPod();
				LgaPackageManager *m = LgaPackageManager::getInstance();
				m->SavePodToFile(pod);
			}*/
			
		}
	});

	connect(ui->pushButton_3, &QPushButton::clicked, [=]() {
		QString path1 = QFileDialog::getOpenFileName(this, tr("images"), "", "*.bmp *.png", nullptr);
		if (path1.isEmpty())
		{
			return;
		}
		QFileInfo file(path1);
		QTextCodec *code = QTextCodec::codecForName("GB2312");
		QString folder = file.absolutePath();
		QString suffix = file.completeSuffix();
		QString str1 = file.fileName();
		QString ext = file.suffix();
		QString str = str1.mid(0, str1.lastIndexOf("_"));
		qDebug() << path1;
		HImage ImageBall, ImageCrossMark, ImageEdge, ImageCap;
		BgaImageProcess *imp = BgaImageProcess::getInstance();
		
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();
		int k = info.listAction.length() == 0 ? 1 : info.listAction.length();
		for (int i = 1; i <= k; i++)
		{
			ACTION_CONFIG ac;
			ac.catchBall = ac.catchSubstrate = 1;
			//ac.catchCM = info.crossMark > 0;
			ac.catchCap = info.capNumbers > 0;
			if (info.listAction.length() > 0)
			{
				ac = info.listAction[i - 1];
			}
			if (ac.catchSubstrate == 1)
			{
				QString s = QString("%1/%2_edge%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
				QFileInfo fileInfo(s);
				if (fileInfo.exists())
				{
					std::string name = code->fromUnicode(s).data();
					HTuple FileName = HTuple(name.data());
					HImage Image;
					ReadImage(&Image, FileName);
					imp->SetSubstrateImage(Image, i);
				}
				if (i == 1)
				{
					QString s = QString("%1/%2_edge.%3").arg(folder).arg(str).arg(suffix);
					QFileInfo fileInfo(s);
					if (fileInfo.exists())
					{
						std::string name = code->fromUnicode(s).data();
						HTuple FileName = HTuple(name.data());
						HImage Image;
						ReadImage(&Image, FileName);
						imp->SetSubstrateImage(Image, i);
					}
				}
			}
			if (ac.catchBall == 1)
			{
				QString s = QString("%1/%2_ball%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
				QFileInfo fileInfo(s);
				if (fileInfo.exists())
				{
					std::string name = code->fromUnicode(s).data();
					HTuple FileName = HTuple(name.data());
					HImage Image;
					ReadImage(&Image, FileName);
					imp->SetBallImage(Image, i);
				}
				if (i == 1)
				{
					QString s = QString("%1/%2_ball.%3").arg(folder).arg(str).arg(suffix);
					QFileInfo fileInfo(s);
					if (fileInfo.exists())
					{
						std::string name = code->fromUnicode(s).data();
						HTuple FileName = HTuple(name.data());
						HImage Image;
						ReadImage(&Image, FileName);
						imp->SetBallImage(Image, i);
					}
				}

			}
			if (ac.catchCap == 1)
			{
				QString s = QString("%1/%2_cap%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
				QFileInfo fileInfo(s);
				if (fileInfo.exists())
				{
					std::string name = code->fromUnicode(s).data();
					HTuple FileName = HTuple(name.data());
					HImage Image;
					ReadImage(&Image, FileName);
					imp->SetCapImage(Image, i);
				}
				if (i == 1)
				{
					QString s = QString("%1/%2_cap.%3").arg(folder).arg(str).arg(suffix);
					QFileInfo fileInfo(s);
					if (fileInfo.exists())
					{
						std::string name = code->fromUnicode(s).data();
						HTuple FileName = HTuple(name.data());
						HImage Image;
						ReadImage(&Image, FileName);
						imp->SetCapImage(Image, i);
					}
				}
			}
			/*if (ac.catchCM == 1)
			{
				QString s = QString("%1/%2_cm%4.%3").arg(folder).arg(str).arg(suffix).arg(i);
				QFileInfo fileInfo(s);
				if (fileInfo.exists())
				{
					std::string name = code->fromUnicode(s).data();
					HTuple FileName = HTuple(name.data());
					HImage Image;
					ReadImage(&Image, FileName);
					imp->SetCrossMarkImage(Image, i);
				}
				if (i == 1)
				{
					QString s = QString("%1/%2_cm.%3").arg(folder).arg(str).arg(suffix);
					QFileInfo fileInfo(s);
					if (fileInfo.exists())
					{
						std::string name = code->fromUnicode(s).data();
						HTuple FileName = HTuple(name.data());
						HImage Image;
						ReadImage(&Image, FileName);
						imp->SetCrossMarkImage(Image, i);
					}
				}
			}*/
		}

		QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

		QDateTime t = QDateTime::currentDateTime();
		imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());

		ResultManager::ERROR_TYPE res = imp->GetInspectResult();

		bool bResult = (res == ResultManager::ERR_PASS || res == ResultManager::ERR_SUBSTRATE_DAMAGE);
		if (!bResult)
		{
			Toast *w = new Toast(this, tr("Test result: Fail"), 250, 36);
			w->toast();
			return;
		}
		else
		{
			BgaPackageManager *m = BgaPackageManager::getInstance();
			BgaImageProcess *imp = BgaImageProcess::getInstance();
			BgaPackageManager::POD_INFO pod = imp->GetPod();
			QString str = QString("Maximum shadow ratio(%2%)\nUse the current configuration for package (%1)?").arg(m->GetPackageType()).arg(pod.maxShadowRatio, 0, 'g', 4);
			QMessageBox::StandardButton rb = QMessageBox::question(NULL, "", str, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
			if (rb == QMessageBox::Yes)
			{
				PACKAGE_INFO info = StaticFunction::GetPackageInfoFromFile();
				if (info.capNumbers > 0)
				{
					info.capArea = pod.meanCapArea;
				}
				StaticFunction::SavePackageInfo(info);
				m->SavePodToFile(pod);
			/*	QString str = BgaPackageManager::getInstance()->GetTeachingString();
				AuthorityManager::getInstance()->AddALog(str);*/
			}
		}
	});

	connect(ui->btnLightsOn, &QPushButton::clicked, [=]() {
		SerialPortManager *sp = SerialPortManager::getInstance();
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();

		sp->SetFourLightBrightnessSync(50, 50, 50, 50);
		
	});

	connect(ui->btnLightsOff, &QPushButton::clicked, [=]() {
		SerialPortManager *sp = SerialPortManager::getInstance();
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();

		sp->SetFourLightBrightnessSync(0, 0, 0, 0);
	});

	connect(ui->btnIn, &QPushButton::clicked, [=]() {
		QHalconWindow *w = ui->widget_Realtime;
		w->ZoomIn();
	});

	connect(ui->btnOut, &QPushButton::clicked, [=]() {
		QHalconWindow *w = ui->widget_Realtime;
		w->ZoomOut();
	});

 /*	connect(ui->pushButton_Reset, &QPushButton::clicked, [=]() {
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Debug");
		QDateTime time = QDateTime::currentDateTime();
		QString currentdate = time.toString("yyyy-MM-dd_hh-mm-ss");
		app.setValue("StartTime", currentdate);
		ImageProcess *imp = ImageProcess::getInstance();
		imp->ResetVerifyTest();
#ifndef QT_NO_DEBUG
		m_totalTimes = m_successTimes = m_failTimes = 0;
		UpdateLcdNumbers();
#endif
		
		Toast *w = new Toast(this, tr("Verification test reset"), 250, 36);
		w->toast();
 	});*/

    AddTimeShow();

    AddCameraShow();
}

void MainWindow::SendResultToHandler(uint8_t b)
{
	BgaPackageManager::INSPECT_PARAM inspectParam = BgaPackageManager::getInstance()->GetParamFromFile();
	PACKAGE_INFO info = StaticFunction::GetPackageInfo();
	if (!info.multiErrorCode)
	{
		b = b == ResultManager::ERR_PASS;
	}

	if (inspectParam.bBypass)
	{
		b = 1;
	}

	char resBuf[10] = { 0 };
	resBuf[0] = 0x8;
	resBuf[2] = 's';
	resBuf[3] = 'i';
	resBuf[4] = 't';
	resBuf[5] = 'e';
	resBuf[6] = m_re.bSite0 ? '0' : '1';
	resBuf[7] = '=';
	resBuf[1] = resBuf[8] = '0' + b;
	resBuf[9] = (resBuf[1] + resBuf[2] + resBuf[3] + resBuf[4] + resBuf[5] + resBuf[6] + resBuf[7] + resBuf[8]) & 0xff;

	SerialPortManager *sp = SerialPortManager::getInstance();
	sp->SendBuffer(resBuf, 10);

	if (ui->listWidget->count() >= 200)
	{
		ui->listWidget->clear();
	}
	QDateTime time = QDateTime::currentDateTime();
	QString str = QString("%1 TX: %2").arg(time.toString("hh:mm:ss"), resBuf);
	ui->listWidget->insertItem(0, str);
}

void MainWindow::UpdateUIWithResult(ResultManager::ERROR_TYPE b, QDateTime time, BOOL bLight)
{
	if (bLight)
	{
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "config");
		int value1 = app.value("redLightCount").toInt();
		app.setValue("redLightCount", value1 + 1);

		int value2 = app.value("white2LightCount").toInt();
		app.setValue("white2LightCount", value2 + 1);

		PACKAGE_INFO info = StaticFunction::GetPackageInfo();
		
		//if (info.crossMark > 0)
		//{
		//	value1 = app.value("blueLightCount").toInt();
		//	app.setValue("blueLightCount", value1 + 1);
		//}

		if (info.capNumbers > 0)
		{
			value1 = app.value("whiteLightCount").toInt();
			app.setValue("whiteLightCount", value1 + 1);
		}


	}
	
	m_re.totalTimes++;
	if (b == ResultManager::ERR_PASS)
	{
		m_re.successTimes++;
	}
	else
	{
		m_re.failTimes++;
		if (b == ResultManager::ERR_BALL_MISSING ||
			b == ResultManager::ERR_BALL_DAMAGE ||
			b == ResultManager::ERR_PAD_DAMAGE)
		{
			m_re.ballDamageTimes++;
		}
		else if (b == ResultManager::ERR_CAP_DAMAGE ||
			b == ResultManager::ERR_CAP_MISSING)
		{
			m_re.capDamageTimes++;
		}
		else if (b == ResultManager::ERR_SUBSTRATE_DAMAGE)
		{
			m_re.substrateDamageTimes++;
		}
	}
	UpdateLcdNumbers();
	UpdateResultList(b, time);
}

void MainWindow::StartAction(int index)
{
	CameraManager *manager = CameraManager::getInstance();
	if (!manager->IsConnected())
	{
		manager->Connect();
	}
	if (manager->IsConnected())
	{
		ui->widget_Realtime->SetDispImageSize(5120, 5120);
		AdjustImageUI(false);
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();
		ui->checkBox->setChecked(false);
	}
	
	QString appName = QCoreApplication::applicationName();
	QSettings app(appName, "Config");
	QString chipType = app.value("ChipType").toString();


	if (chipType.toLower() == "bga")
	{
		BgaImageProcess *imp = BgaImageProcess::getInstance();
		if (index == 1)
		{
			//ui->widget_Realtime->setDispImageSize(5120, 5120);
			//ui->widget_Realtime->SetProcessing(false);

			//SerialPortManager *sp = SerialPortManager::getInstance();
			//LgaPackageManager::PACKAGE_INFO info = LgaPackageManager::getInstance()->getPackageInfo();
			//sp->SetTwoLightBrightnessSync(info.lightConfigPad.brightness1, info.lightConfigPad.brightness2);
			QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

			QDateTime t = QDateTime::currentDateTime();

			imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());
		}
		else
		{
			QString appName = QCoreApplication::applicationName();
			QSettings app(appName, "Debug");
			int triggerDelay = app.value("triggerDelay").toInt();
			if (triggerDelay < 100)
			{
				triggerDelay = TRIGGER_DELAY_MS;
			}
			DelayMs(triggerDelay);
		}
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();
		SerialPortManager *sp = SerialPortManager::getInstance();
		//	CameraManager *manager = CameraManager::getInstance();
			//ui->widget_Realtime->SetProcessing(false);
		HImage ImageBall, ImageCrossMark, ImageIC, ImageCap;
		if (info.listAction.length() == 0)
		{
			m_lastMeanGray = 0;
		/*	if (info.crossMark > 0)
			{
				HImage img = CatchCMImage();
				imp->SetCrossMarkImage(img, index);
			}*/
			//if (ac.catchBall == 1)
			{
				HImage img = CatchBallImage();
				imp->SetBallImage(img, index);
			}
			if (info.capNumbers > 0)
			{
				HImage img = CatchCapImage();
				imp->SetCapImage(img, index);

			}
			//if (ac.catchSubstrate == 1)
			{
				HImage img = CatchSubStrateImage();
				imp->SetSubstrateImage(img, index);
			}
		}
		else
		{
			ACTION_CONFIG ac = info.listAction[index - 1];
			qDebug() << "catch" << index;
			m_lastMeanGray = 0;
	/*		if (info.crossMark > 0 && ac.catchCM == 1)
			{
				HImage img = CatchCMImage();
				imp->SetCrossMarkImage(img, index);
			}*/
			if (ac.catchBall == 1)
			{
				HImage img = CatchBallImage();
				imp->SetBallImage(img, index);
			}
			if (info.capNumbers > 0 && ac.catchCap == 1)
			{
				HImage img = CatchCapImage();
				imp->SetCapImage(img, index);
			}
			if (ac.catchSubstrate == 1)
			{
				HImage img = CatchSubStrateImage();
				imp->SetSubstrateImage(img, index);
			}
			if (index < info.listAction.count())
			{
				ACTION_CONFIG ac2 = info.listAction[index];
				sp->SendNextPos(ac2.x, ac2.y);
				qDebug() << "SendNextPos" << index << ac2.x << ac2.y;
				return;
			}
		}

		sp->SetFourLightBrightnessSync(0, 0, 0, 0);
		QThread::msleep(100);

		//ui->widget_Realtime->SetProcessing(true);
		QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

		QDateTime t = QDateTime::currentDateTime();
		imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());
		ResultManager::ERROR_TYPE res = imp->GetInspectResult();

		QString path = QString("%1/Results/result.wtlog").arg(QCoreApplication::applicationDirPath());
		SaveResultToFile(res, path, t);

		UpdateUIWithResult(res, t, TRUE);

		if (info.multiErrorCode)
		{
			SendResultToHandler(res);
		}
		else
		{
			SendResultToHandler(res == ResultManager::ERR_PASS);
		}
	}
	else if (chipType.toLower() == "lga")
	{
		qDebug() << __FUNCTION__ << index;
		LgaImageProcess *imp = LgaImageProcess::getInstance();
		if (index == 1)
		{
			//ui->widget_Realtime->setDispImageSize(5120, 5120);
			//ui->widget_Realtime->SetProcessing(false);

			//SerialPortManager *sp = SerialPortManager::getInstance();
			//LgaPackageManager::PACKAGE_INFO info = LgaPackageManager::getInstance()->getPackageInfo();
			//sp->SetTwoLightBrightnessSync(info.lightConfigPad.brightness1, info.lightConfigPad.brightness2);
			QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

			QDateTime t = QDateTime::currentDateTime();

			imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());
		}
		else
		{
			QString appName = QCoreApplication::applicationName();
			QSettings app(appName, "Debug");
			int triggerDelay = app.value("triggerDelay").toInt();
			if (triggerDelay < 100)
			{
				triggerDelay = TRIGGER_DELAY_MS;
			}
			DelayMs(triggerDelay);
		}
		PACKAGE_INFO info = StaticFunction::GetPackageInfo();
		SerialPortManager *sp = SerialPortManager::getInstance();
		//	CameraManager *manager = CameraManager::getInstance();
			//ui->widget_Realtime->SetProcessing(false);
		HImage ImageBall, ImageCrossMark, ImageIC, ImageCap;
		if (info.listAction.length() == 0)
		{
			m_lastMeanGray = 0;

			//if (ac.catchBall == 1)
			{
				HImage img = CatchBallImage();
				imp->SetBallImage(img, index);
			}
			if (info.capNumbers > 0)
			{
				HImage img = CatchCapImage();
				imp->SetCapImage(img, index);

			}
			//if (ac.catchSubstrate == 1)
			{
				HImage img = CatchSubStrateImage();
				imp->SetSubstrateImage(img, index);
			}
		}
		else
		{
			ACTION_CONFIG ac = info.listAction[index - 1];
			qDebug() << "catch" << index << "list" << index - 1;
			m_lastMeanGray = 0;
			
			if (ac.catchBall == 1)
			{
				HImage img = CatchBallImage();
				imp->SetBallImage(img, index);
			}
			if (info.capNumbers > 0 && ac.catchCap == 1)
			{
				HImage img = CatchCapImage();
				imp->SetCapImage(img, index);
			}
			if (ac.catchSubstrate == 1)
			{
				HImage img = CatchSubStrateImage();
				imp->SetSubstrateImage(img, index);
			}
			if (index < info.listAction.count())
			{
				ACTION_CONFIG ac2 = info.listAction[index];
				sp->SendNextPos(ac2.x, ac2.y);
				qDebug() << "SendNextPos" << index << ac2.x << ac2.y;
				return;
			}
		}
		sp->SetFourLightBrightnessSync(0, 0, 0, 0);
		if (index == info.listAction.count())
		{
			qDebug() << "StartAnalysis";
			m_re.cacthIndex = 0;
			DelayMs(100);
			StartAnalysis();
		}
	}

}

void MainWindow::StartAnalysis()
{
	qDebug() << __FUNCTION__;
	QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());

	QDateTime t = QDateTime::currentDateTime();
	LgaImageProcess *imp = LgaImageProcess::getInstance();
	imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());

	ResultManager::ERROR_TYPE b = imp->GetInspectResult();
	qDebug() << "final result:" << b;
	QString path = QString("%1/Results/result.wtlog").arg(QCoreApplication::applicationDirPath());
	SaveResultToFile(b, path, t);

	QTimer::singleShot(50, [=] {
		imp->ShowAndSave(TRUE);
		SendResultToHandler(b);
		UpdateUIWithResult(b, t, TRUE);
	});
}

BOOL MainWindow::JudgeRetry(int actionNum, BOOL bTeaching)
{
	UNREFERENCED_PARAMETER(actionNum);
	BOOL bContinue = FALSE;
	{
		if (bTeaching)
		{
			emit TeachingFinishedEvent();
			QMessageBox::warning(nullptr, "", QStringLiteral("Teaching fail, can't catch normal images."));
		}
		else
		{
			qDebug() << "action , no normal images, continue";
			bContinue = TRUE;
		}
	}	
	return bContinue;
}

HImage MainWindow::CatchSubStrateImage()
{
	PACKAGE_INFO info = StaticFunction::GetPackageInfo();
	SerialPortManager *sp = SerialPortManager::getInstance();
	CameraManager *manager = CameraManager::getInstance();

	if (!manager->IsConnected())
	{
		manager->Connect();
	}
	HImage ImagePad;
	int c = 0;
	while (c < RETRY_NUM)
	{
		sp->SetFourLightBrightnessSync(info.lightConfigSubstrate.brightness1, info.lightConfigSubstrate.brightness2, info.lightConfigSubstrate.brightness3, info.lightConfigSubstrate.brightness4);
		manager->SoftwareTrigger();
		ImagePad = manager->GetLatestImage();
		double mean = GetGrayMean(ImagePad);
		qDebug() << "sub image mean gray:" << mean;
		if (/*mean < MAX_GRAY &&*/ mean > 1)
		{
			break;
		}
		else
		{
			DelayMs(DELAY_MS_NUM);
		}
		c++;
	}
	return ImagePad;
}

HImage MainWindow::CatchCapImage()
{
	PACKAGE_INFO info = StaticFunction::GetPackageInfo();
	SerialPortManager *sp = SerialPortManager::getInstance();
	CameraManager *manager = CameraManager::getInstance();

	if (!manager->IsConnected())
	{
		manager->Connect();
	}
	HImage ImagePad;
	int c = 0;
	while (c < RETRY_NUM)
	{
		sp->SetFourLightBrightnessSync(info.lightConfigCap.brightness1, info.lightConfigCap.brightness2, info.lightConfigCap.brightness3, info.lightConfigCap.brightness4);
		manager->SoftwareTrigger();

		ImagePad = manager->GetLatestImage();
		double mean = GetGrayMean(ImagePad);
		qDebug() << "cap image mean gray:" << mean;
		if (/*mean < MAX_GRAY && */mean > 1)
		{
			break;
		}
		else
		{
			DelayMs(DELAY_MS_NUM);
		}
		c++;
	}
	return ImagePad;
}

HImage MainWindow::CatchCMImage()
{
	PACKAGE_INFO info = StaticFunction::GetPackageInfo();
	SerialPortManager *sp = SerialPortManager::getInstance();
	CameraManager *manager = CameraManager::getInstance();

	if (!manager->IsConnected())
	{
		manager->Connect();
	}
	HImage ImagePad;
	int c = 0;
	while (c < RETRY_NUM)
	{
		sp->SetFourLightBrightnessSync(info.lightConfigCM.brightness1, info.lightConfigCM.brightness2, info.lightConfigCM.brightness3, info.lightConfigCM.brightness4);
		manager->SoftwareTrigger();

		ImagePad = manager->GetLatestImage();
		double mean = GetGrayMean(ImagePad);
		qDebug() << "cm image mean gray:" << mean;
		if (/*mean < MAX_GRAY && */mean > 1)
		{
			break;
		}
		else
		{
			DelayMs(DELAY_MS_NUM);
		}
		c++;
	}
	return ImagePad;
}

HImage MainWindow::CatchBallImage()
{
	PACKAGE_INFO info = StaticFunction::GetPackageInfo();
	SerialPortManager *sp = SerialPortManager::getInstance();
	CameraManager *manager = CameraManager::getInstance();

	if (!manager->IsConnected())
	{
		manager->Connect();
	}
	HImage ImagePad;
	int c = 0;
	while (c < RETRY_NUM)
	{
		sp->SetFourLightBrightnessSync(info.lightConfigBall.brightness1, info.lightConfigBall.brightness2, info.lightConfigBall.brightness3, info.lightConfigBall.brightness4);
		manager->SoftwareTrigger();

		ImagePad = manager->GetLatestImage();
		double mean = GetGrayMean(ImagePad);
		qDebug() << "ball image mean gray:" << mean;
		if (/*mean < MAX_GRAY && */mean > 1)
		{
			break;
		}
		else
		{
			DelayMs(DELAY_MS_NUM);
		}
		c++;
	}
	return ImagePad;
}


//void MainWindow::StartAction4(BOOL bTeaching)
//{
//	//qDebug() << __FUNCTION__;
//	PACKAGE_INFO info = StaticFunction::GetPackageInfo();
//	SerialPortManager *sp = SerialPortManager::getInstance();
////	CameraManager *manager = CameraManager::getInstance();
//	//ui->widget_Realtime->SetProcessing(false);
//	HImage ImageBall, ImageCrossMark, ImageIC, ImageCap;
//	ImageProcess *imp = ImageProcess::getInstance();
//	//int count = 0;
//	m_lastMeanGray = 0;
//	if (info.crossMark > 0)
//	{
//		HImage img = CatchCMImage();
//		imp->SetCrossMarkImage(img);
//	}
//	{
//		HImage img = CatchBallImage();
//		imp->SetBallImage(img);
//	}
//
//	if (info.capNumbers > 0)
//	{
//		HImage img = CatchCapImage();
//		imp->SetCapImage(img);
//
//	}
//	{
//		HImage img = CatchSubStrateImage();
//		imp->SetSubstrateImage(img);
//	}
//	
//
//
//	sp->SetFourLightBrightnessSync(0, 0, 0, 0);
//	QThread::msleep(100);
//	
//	//ui->widget_Realtime->SetProcessing(true);
//	QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());
//
//	QDateTime t = QDateTime::currentDateTime();
//	imp->SetWinHandleAndSavePath(ui->widget_Realtime, dir_str, t, GetRunInfo());
//	ResultManager::ERROR_TYPE res = imp->GetInspectResult();
//
//	if (!bTeaching)
//	{
//		QString path = QString("%1/Results/result.wtlog").arg(QCoreApplication::applicationDirPath());
//		SaveResulToFile(res, path, t);
//
//		UpdateUIWithResult(res, t, TRUE);
//
//		if (info.multiErrorCode)
//		{
//			SendResultToHandler(res);
//		}
//		else
//		{
//			SendResultToHandler(res == ResultManager::ERR_PASS);
//		}
//
//	}
//	else {
//		emit TeachingFinishedEvent();
//		if (res == ResultManager::ERR_PASS || res == ResultManager::ERR_SUBSTRATE_DAMAGE)
//		{
//			BgaPackageManager *m = BgaPackageManager::getInstance();
//			ImageProcess *imp = ImageProcess::getInstance();
//			BgaPackageManager::POD_INFO pod = imp->GetPod();
//			QString str = QString("Maximum shadow ratio(%2%)\nUse the current configuration for package (%1)?").arg(m->GetPackageType()).arg(pod.maxShadowRatio, 0, 'g', 4); QMessageBox::StandardButton rb = QMessageBox::question(NULL, "", str, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
//			if (rb == QMessageBox::Yes)
//			{
//				BgaPackageManager::PACKAGE_INFO info = m->GetPackageInfoFromFile();
//
//				if (info.capNumbers > 0)
//				{
//					info.capArea = pod.meanCapArea;
//				}
//				m->SavePackageInfo(info);
//				m->SavePodToFile(pod);
//			}
//		}
//		else {
//			Toast *w = new Toast(this, tr("Test result: Fail"), 250, 36);
//			w->toast();
//			return;
//		}
//	}
//}

void MainWindow::WaitForComData()
{
	QSerialPort *m_serial = SerialPortManager::getInstance()->GetHandlerCom();

    QObject::connect(m_serial, &QSerialPort::readyRead,this, [=](){
		static QByteArray dataBuffer;
        QByteArray bytes = m_serial->readAll();
		if (!bytes.isEmpty())
		{
			qDebug() <<"recv handler data:" <<bytes;
			if (ui->listWidget->count() >= 200)
			{
				ui->listWidget->clear();
			}
			QDateTime time = QDateTime::currentDateTime();
			QString str = QString("%1 RX: %2").arg(time.toString("hh:mm:ss"), bytes.data());
			ui->listWidget->insertItem(0, str);
			dataBuffer += bytes;
			
			if (dataBuffer.length() == 14) 
			{
				char *buf = dataBuffer.data();
				if (buf[0] == '@' &&
					buf[1] == 'Q' &&
					buf[2] == 'u' &&
					buf[3] == 'e' &&
					buf[4] == 'r' &&
					buf[5] == 'y' &&
					buf[6] == 'V' &&
					buf[7] == 'e' &&
					buf[8] == 'r' &&
					buf[9] == 's' &&
					buf[10] == 'i' &&
					buf[11] == 'o' &&
					buf[12] == 'n' &&
					buf[13] == '+'
					)
				{
					SerialPortManager::getInstance()->SendVersion();
					dataBuffer.clear();
				}
			}
			if (dataBuffer.length() >= 9)
			{
				char *buf = dataBuffer.data();
				if (buf[0] == 0x7 &&
					buf[3] == 'B' &&
					buf[4] == 'D' &&
					buf[5] == 'A' &&
					buf[6] == 'O' &&
					buf[7] == 'I'
					)
				{
                   // qDebug() << "process rx data:" << dataBuffer;
					BOOL bSite0 = buf[1] - '0';
					BOOL bSite1 = buf[2] - '0';
					if (bSite0 + bSite1 == 1)
					{
						m_re.bSite0 = bSite0;
					}
					m_re.cacthIndex = 0;
					QVariant v = ui->pushButton_Start->property("Started");
					bool b = v.toBool();
					if (b)
					{
						PACKAGE_INFO info = StaticFunction::GetPackageInfo();
						if (info.listAction.count() == 0)
						{
							StartAction(1);
						}
						else
						{
							ACTION_CONFIG ac = info.listAction[0];
							SerialPortManager::getInstance()->SendNextPos(ac.x, ac.y);
							qDebug() << "SendNextPos" << 0 << ac.x << ac.y;
						}
					}
						
					dataBuffer.clear();
				}
				else if (buf[3] == 'N' && buf[4] == 'L' && buf[5] == 'O' && buf[6] == 'T' && buf[7] == '#')
				{
					QString str = QString::fromUtf8(dataBuffer);
					int firstHash = str.indexOf('#');
					// 找到最后一个#的位置
					int lastHash = str.lastIndexOf('#');
					if (firstHash != -1 && lastHash != -1 && firstHash < lastHash) {
						m_re.lotId = str.mid(firstHash + 1, lastHash - firstHash - 1);
						//qDebug() << "lot name：" << m_lotName;
					}
					else
					{
						m_re.lotId = QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss");
						qDebug() << "nlot wrong string";
					}
					m_re.startTime = QDateTime::currentDateTime();
					qDebug() << "NLOT:" << m_re.lotId;
					dataBuffer.clear();
					m_re.successTimes = m_re.failTimes = m_re.totalTimes = 0;
					m_re.ballDamageTimes = m_re.capDamageTimes = m_re.substrateDamageTimes = 0;
				}
				else if (buf[3] == 'E' && buf[4] == 'L' && buf[5] == 'O' && buf[6] == 'T' && buf[7] == '#'&& buf[8] == '#')
				{
					m_re.endTime = QDateTime::currentDateTime();
					
					qDebug() << "ELOT:" << dataBuffer;
					if (m_re.lotId.length() > 0)
					{
						ImageSaveManager *ism = ImageSaveManager::getInstance();
						ism->SaveSummaryInfo(m_re);
					}
					else
					{
						qDebug() << "ELOT no lot id";
					}
					dataBuffer.clear();
				}
			}
			else if (dataBuffer.length() >= 7)
			{
				char *buf = dataBuffer.data();
				if (buf[0] == 0x5 &&
					buf[1] == '1' &&
					buf[2] == '0' &&
					buf[3] == 'T' &&
					buf[4] == 'R' &&
					buf[5] == 'G'
					)
				{
					QVariant v = ui->pushButton_Start->property("Started");
					bool b = v.toBool();
					if (b)
					{
						StartAction(++m_re.cacthIndex);
					}

					dataBuffer.clear();
				}
			}
			else if (dataBuffer.length() < 7)
			{
				//qDebug() << dataBuffer;
			}
		}
        bytes.clear();
    });
    
}

void MainWindow::AddTimeShow()
{
    QTimer *timer = new QTimer(this);

    //新建定时器
    connect(timer, &QTimer::timeout, [=](){
        QDateTime time = QDateTime::currentDateTime();

        //获取系统现在的时间
        int h = time.time().hour();
        int m = time.time().minute();
        int s = time.time().second();

        if(h+m+s == 0)
        {
           ClearExpiredFiles();
        }

        QString str = time.toString("yyyy-MM-dd hh:mm:ss");
        ui->lcdNumber_Time->display(str);//显示时间
    });

    //关联定时器计满信号和相应的槽函数

    timer->start(1000);
}

void MainWindow::AddCameraShow()
{
    CameraManager *manager = CameraManager::getInstance();

	
	
    connect(manager, &CameraManager::disconnectEvent, this, [=]{
		QVariant v = ui->pushButton_Start->property("Started");
		bool b = v.toBool();
		if (b)
		{
			ui->widget_Realtime->GetHalconBuffer()->ClearWindow();
			ui->widget_Realtime->GetHalconBuffer()->FlushBuffer();
			ui->pushButton_Start->setProperty("Started", false);
			ui->pushButton_Start->setText(tr("Start"));
			ui->pushButton_Start->setIcon(QIcon(":/images/start.png"));

			Toast *w = new Toast(this, tr("Disconnected with camera"), 250, 36);
			w->toast();
		}
		ui->pushButton_Start->setProperty("Started", manager->IsConnected());
       
    });

	//connect(manager, &CameraManager::rxImageEvent, [=](int iW, int iH, uint8_t *buffer)
	//{
	//	HImage m_hoImage;
	//	GenImage1(&m_hoImage, "byte", iW, iH, reinterpret_cast<Hlong>(buffer));
	//	//QHalconWindow *imageView = static_cast<QHalconWindow *>(QWidget::find(reinterpret_cast<WId>(hWnd)));

	//	//if (imageView)
	//	{
	//		ui->widget_Realtime->GetHalconBuffer()->SetColor("green");
	//		ui->widget_Realtime->GetHalconBuffer()->DispImage(m_hoImage);
	//		ui->widget_Realtime->GetHalconBuffer()->DispCross(iH / 2, iW / 2, 50, 0);
	//		ui->widget_Realtime->GetHalconBuffer()->FlushBuffer();
	//	}
	//});

	connect(manager, &CameraManager::connectedEvent, [=](int state, int64_t, int64_t)
	{
		if (state == 0)
		{
			/*	Toast *w = new Toast(this, tr("Connect fail"), 180, 30);
				w->toast();*/

			return;
		}
		else if (state == 1)
		{
			/*auto func = [](int iW, int iH, uint8_t *buffer, HWND hWnd) ->void{
				HImage m_hoImage;
				GenImage1(&m_hoImage, "byte", iW, iH, reinterpret_cast<Hlong>(buffer));
				QHalconWindow *imageView = static_cast<QHalconWindow *>(QWidget::find(reinterpret_cast<WId>(hWnd)));

				if (imageView)
				{
					imageView->GetHalconBuffer()->SetColor("green");
					imageView->GetHalconBuffer()->DispImage(m_hoImage);
					imageView->GetHalconBuffer()->DispCross(iH / 2, iW / 2, 50, 0);
					imageView->GetHalconBuffer()->FlushBuffer();
				}
			};*/
			//manager->SetState(ui->checkBox->isChecked());
			auto func = [](int iW, int iH, HImage m_hoImage, HWND hWnd) ->void {

				QHalconWindow *imageView = static_cast<QHalconWindow *>(QWidget::find(reinterpret_cast<WId>(hWnd)));

				if (imageView)
				{

					imageView->GetHalconBuffer()->SetColor("green");
					imageView->GetHalconBuffer()->DispObj(m_hoImage);
					imageView->GetHalconBuffer()->DispCross(iH / 2, iW / 2, 500, 0);
					imageView->GetHalconBuffer()->FlushBuffer();
				}

			};
			manager->SetCameraLive(ui->checkBox->isChecked());
			manager->GrabImage(func, reinterpret_cast<HWND>(ui->widget_Realtime->winId()));
			//   manager->GrabImage(reinterpret_cast<HWND>(ui->widget_Realtime->winId()));
		   //	manager->StartStreamGrabbing();
			AdjustImageUI(false);
		}
		else if (state == 2)
		{
			Toast *w = new Toast(this, tr("No Camera"), 180, 30);
			w->toast();
			ui->pushButton_Start->setText(tr("Start"));
			ui->pushButton_Start->setIcon(QIcon(":/images/start.png"));
			//   m_timerStart->stop();
			 //  ui->pushButton_StaticProcess->setDisabled(false);
			ui->pushButton_Start->setDisabled(false);
			ui->pushButton_Start->setProperty("Started", false);
			UpdateStatusBar();
		}
		else if (state == ERROR_CAMERA_HAS_BEEN_OPENED)
		{
			Toast *w = new Toast(this, tr("The camera has been opened"), 300, 30);
			w->toast();
			ui->pushButton_Start->setText(tr("Start"));
			ui->pushButton_Start->setIcon(QIcon(":/images/start.png"));
			//   m_timerStart->stop();
			 //  ui->pushButton_StaticProcess->setDisabled(false);
			ui->pushButton_Start->setDisabled(false);
			ui->pushButton_Start->setProperty("Started", false);
			UpdateStatusBar();
		}
		else
		{
			Toast *w = new Toast(this, tr("The camera error"), 280, 30);
			w->toast();
			ui->pushButton_Start->setText(tr("Start"));
			ui->pushButton_Start->setIcon(QIcon(":/images/start.png"));
			//   m_timerStart->stop();
			 //  ui->pushButton_StaticProcess->setDisabled(false);
			ui->pushButton_Start->setDisabled(false);
			ui->pushButton_Start->setProperty("Started", false);
			UpdateStatusBar();
		}
	});
}

void MainWindow::SaveResultToFile(ResultManager::ERROR_TYPE b, QString path, QDateTime time)
{
    ResultManager::RESULT_DEF res;
    res.time = time;
	res.people = m_re.operatorName;
	res.product = m_re.productNum;
    res.result = b;

    ResultManager::getInstance()->SaveResultToLogFile(path, res);
}

void MainWindow::UpdateLcdNumbers()
{
    ui->lcdNumber_Total->display(m_re.totalTimes);
    ui->lcdNumber_OK->display(m_re.successTimes);
    ui->lcdNumber_NG->display(m_re.failTimes);
}

void MainWindow::UpdateResultList(ResultManager::ERROR_TYPE b, QDateTime time)
{
    ui->tableWidget->insertRow(0);
   // QDateTime time = QDateTime::currentDateTime();
	m_re.operatorName = ui->lineEditOperator->text();
	m_re.productNum = ui->comboBoxType->currentText();
	m_re.packageName = ui->comboBox->currentText();

	//{
	//	QTableWidgetItem *item = new QTableWidgetItem(m_operatorName);
	//	item->setTextAlignment(Qt::AlignCenter);
	//	//            item->setTextColor(QColor(200,111,100));
	//	item->setFont(QFont("Helvetica", 12));
	//	ui->tableWidget->setItem(0, 0, item);
	//}

	//{
	//	QTableWidgetItem *item = new QTableWidgetItem(m_productNum);
	//	item->setTextAlignment(Qt::AlignCenter);
	//	//            item->setTextColor(QColor(200,111,100));
	//	item->setFont(QFont("Helvetica", 12));
	//	ui->tableWidget->setItem(0, 1, item);
	//}

    {
        QTableWidgetItem *item = new QTableWidgetItem(time.toString("yyyy-MM-dd"));
        item->setTextAlignment(Qt::AlignCenter);
//            item->setTextColor(QColor(200,111,100));
        item->setFont(QFont("Helvetica", 12));
        ui->tableWidget->setItem(0, 0, item);
    }
    {
       // QString str = time.toString("hh:mm:ss:zzz");
        QTableWidgetItem *item = new QTableWidgetItem(time.toString("hh:mm:ss"));
        item->setTextAlignment(Qt::AlignCenter);
//            item->setTextColor(QColor(200,111,100));
        item->setFont(QFont("Helvetica", 12));

        ui->tableWidget->setItem(0, 1, item);
    }


	{
		QTableWidgetItem *item = new QTableWidgetItem("P");
		item->setTextColor(QColor(255, 255, 255));
		item->setBackgroundColor(QColor(0, 200, 0));
		if (b != ResultManager::ERR_PASS)
		{
			item->setText("F");

			item->setBackgroundColor(QColor(200, 0, 0));
		}
		item->setTextAlignment(Qt::AlignCenter);
		//    item->setTextColor(QColor(200,111,100));
		item->setFont(QFont("Helvetica", 20, QFont::Bold));

		ui->tableWidget->setItem(0, 2, item);
	}

}

void MainWindow::closeEvent(QCloseEvent *event)
{
	QMessageBox::StandardButton rb = QMessageBox::question(NULL, "Exit", "Do you want to exit?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
	if (rb == QMessageBox::Yes)
	{
		CameraManager *manager = CameraManager::getInstance();
		disconnect(manager);
		event->accept();  //接受退出信号，程序退出
	}
	else {
		event->ignore();
	}
    
  //  disconnect(m_timerStart);
}

void MainWindow::ClearExpiredFiles()
{
	BgaPackageManager::INSPECT_PARAM param = BgaPackageManager::getInstance()->GetParamFromFile();
    QString dir_str = QString("%1/TempImages").arg(QCoreApplication::applicationDirPath());
    QDir dir;
    if (dir.exists(dir_str))
    {
        QDir dir1(dir_str);
        dir1.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
        QFileInfoList list = dir1.entryInfoList();

        int file_count = list.count();
        if(file_count > 0)
        {
            QStringList string_list;
            for(int i=0; i<file_count; i++)
            {
                QFileInfo file_info = list.at(i);
                QDateTime birth = file_info.birthTime();
                QDateTime now = QDateTime::currentDateTime();

                if (now > birth.addDays(param.saveDays))
                {
                    deleteDirectory(file_info.filePath());
                }
            }
        }
    }
}
